package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.NumberUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Resource
    private MapApi mapApi;
    //默认地址 flag 0：取消默认，1：设为默认
    private static final Integer NON_DEFAULT = 0;
    //取消默认地址 flag 0：取消默认，1：设为默认
    private static final Integer DEFAULT = 1;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if (CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增地址
     *
     * @param addressBookDto 地址信息
     */
    @Override
    @Transactional
    public void addAddressBook(AddressBookUpsertReqDTO addressBookDto) {
        AddressBook addressBook = new AddressBook();
        org.springframework.beans.BeanUtils.copyProperties(addressBookDto, addressBook);
        addressBook.setUserId(UserContext.currentUserId());
        //1通过地址查询经纬度
        //1.1 组装地址String
        String address = addressBook.getProvince() + addressBook.getCity() + addressBook.getCounty() + addressBook.getAddress();
        LocationResDTO locationByAddress = mapApi.getLocationByAddress(address);
        String location = locationByAddress.getLocation();
        if (!StringUtils.hasText(location)) {
            throw new RuntimeException("地址解析失败,请输入正确地址");
        }
        // 经纬度
        String[] split = location.split(",");
        addressBook.setLon(NumberUtils.parseDouble(split[0]));
        addressBook.setLat(NumberUtils.parseDouble(split[1]));
        //2.如果设置为默认地址，需要删除其他地址的默认
        if (addressBook.getIsDefault() == 1) {
            super.lambdaUpdate()
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault, 1)
                    .update(new AddressBook().setIsDefault(0));
        }
        //3保存
        super.save(addressBook);
    }

    /**
     * 修改地址
     *
     * @param id             地址id
     * @param addressBookDto 地址信息
     */
    @Override
    @Transactional
    public void updateAddressBook(Long id, AddressBookUpsertReqDTO addressBookDto) {
        //删除原来的 地址
        super.removeById(id);
        //新增
        this.addAddressBook(addressBookDto);
    }

    /**
     * 设置默认地址
     *
     * @param flag 0：取消默认，1：设为默认
     * @param id   地址id
     */
    @Override
    public void setDefault(Integer flag, Long id) {
        //如果设为默认，需要删除其他地址的默认
        if (flag.equals( DEFAULT) ) {
            super.lambdaUpdate()
                    .eq(AddressBook::getUserId, UserContext.currentUserId())
                    .eq(AddressBook::getIsDefault, DEFAULT)
                    .update(new AddressBook().setIsDefault(NON_DEFAULT));
        }
        //修改
        super.update(Wrappers.<AddressBook>lambdaUpdate()
                .set(AddressBook::getIsDefault, flag)
                .eq(AddressBook::getId, id)
        );
    }

    /**
     * 获取默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        return super.getOne(Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId()).eq(AddressBook::getIsDefault, DEFAULT));
    }
}
